
import {wxUtils} from "../wx/wxUtils";
import {apiUtils} from "../web/api/ApiUtils";
import { GameVar } from "../game/GameVar";
const {ccclass, property} = cc._decorator;

const MOVEDIS = 500;
const MOVETIME = 0.5;

@ccclass
export default class RankLayer extends cc.Component {
    @property(cc.Node)
    bg: cc.Node = null;
    @property(cc.Label)
    title: cc.Label = null;
    @property(cc.Label)
    btnLabel: cc.Label = null;

    private _curShow = 'friendRank';
    private _closing = false;
    private _allRank = {items:[]};

    onLoad () {
        let block = this.node.getChildByName('splash');  // 屏蔽点击的全屏黑色半透背景
        block.on(cc.Node.EventType.TOUCH_END, (event: cc.Event.EventTouch) => {
            this.close();
        }, this);
    }

    show() {
        this.resetRanAll();
        this.node.active = true;
        this.bg.x -= MOVEDIS;
        this.showRankFriend();
        wxUtils.postMessage({cmd: 'showRankList', moveTime: MOVETIME, moveDis: MOVEDIS});
        this.bg.runAction(cc.moveBy(MOVETIME, cc.v2(MOVEDIS, 0)));
    }

    async resetRanAll() {
        let rankData = await apiUtils.reqRankAll();
        if (rankData) {
            this._allRank = {items:[]};
            let selfID = GameVar.userInfo.uid;
            for (let ix = 0; ix < rankData.info.length; ix++) {
                const e = rankData.info[ix];
                e.uid === selfID && (this._allRank['selfIndex']=ix);
                this._allRank.items.push({
                    nickName: e.nick,
                    avatarUrl: e.headUrl,
                    score: e.score
                });
            }
        }
    }

    showRankAll() {
        this._curShow = 'allRank';
        this.title.string = '全服积分排行榜';
        this.btnLabel.string = '查看好友排名';
        wxUtils.postMessage({cmd: 'showRankAll', rankData: this._allRank});
    }

    showRankFriend() {
        this._curShow = 'friendRank';
        this.title.string = '好友积分排行榜';
        this.btnLabel.string = '查看全服排名';
        wxUtils.postMessage({cmd: 'showRankFriend'});
    }

    clickOther() {
        if (this._curShow === 'friendRank') {
            this.showRankAll();
        } else if (this._curShow === 'allRank') {
            this.showRankFriend();
        }
    }

    close () {
        if (this._closing) {
            return;
        }
        this._closing = true;
        wxUtils.postMessage({cmd: 'hideRankList', moveTime: MOVETIME, moveDis: MOVEDIS});
        this.bg.runAction(cc.sequence(
            cc.moveBy(MOVETIME, cc.v2(-MOVEDIS, 0)),
            cc.callFunc(()=>{
                this._closing = false;
                this.bg.x += MOVEDIS;
                this.node.active = false;
                wxUtils.postMessage({cmd: 'showRankFriendTop'});
            })
        ));
    }
}
